package org.dtp.listener;

import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigFile;
import com.ctrip.framework.apollo.ConfigService;
import com.ctrip.framework.apollo.core.enums.ConfigFileFormat;
import org.dtp.DynamicThreadPoolManager;
import org.dtp.config.DynamicThreadPoolProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * @ClassName ApolloConfigUpdateListener
 * @Description Apollo监听
 * @Author wangyiqi
 * @Date 2021-08-11-20:49
 **/
public class ApolloConfigUpdateListener {

    @Value("${apollo.bootstrap.namespaces:application}")
    private String namespace;

    @Autowired
    private DynamicThreadPoolManager dynamicThreadPoolManager;

    @Resource
    private DynamicThreadPoolProperties dynamicThreadPoolProperties;

    @PostConstruct
    public void init() {
        initConfigUpdateListener();
    }

    private void initConfigUpdateListener() {
        String apolloNamespace = namespace;
        if (StringUtils.hasText(dynamicThreadPoolProperties.getApolloNamespace())) {
            apolloNamespace = dynamicThreadPoolProperties.getApolloNamespace();
        }

        String finalApolloNamespace = apolloNamespace;

        Config config = ConfigService.getConfig(finalApolloNamespace);

        config.addChangeListener(changeEvent -> {
            String namespace = changeEvent.getNamespace();
            int lastPointIndex = namespace.indexOf(".");
            ConfigFileFormat configFileFormat = ConfigFileFormat.fromString(namespace.substring(lastPointIndex + 1));
            ConfigFile configFile = ConfigService.getConfigFile(namespace.substring(0, lastPointIndex), configFileFormat);
            String content = configFile.getContent();

            if (ConfigFileFormat.isPropertiesCompatible(configFileFormat)) {
                dynamicThreadPoolProperties.refreshYaml(content);
            } else {
                dynamicThreadPoolProperties.refresh(content);
            }
            dynamicThreadPoolManager.refreshThreadPoolExecutor(dynamicThreadPoolProperties.getExecutors());
        });
    }

}
